<?php

namespace app\services;

use plugin\admin\app\model\User;
use plugin\admin\app\model\UserUpline;

class UpLineService
{
    public static function get($userId, $withOutParent = false)
    {
        $upLine = UserUpline::where('user_id', $userId)->first();

        if (empty($upLine['upline'])) {
            return [];
        }

        $line = array_filter(explode(',', $upLine['upline']));

        if ($withOutParent) {
            $user = User::select(['parent_id'])->where('id', $userId)->first();
            return array_diff($line, [$user['parent_id']]);
        }

        return $line;
    }

    public static function children($userId)
    {
        $userId = ',' . $userId . ',';
        return UserUpline::where('upline', 'like', "%$userId%")->get()->toArray();
    }

    public static function isSameLine($userId, $checkUserId)
    {
        $upLine = UserUpline::where('user_id', $userId)->first();
        $checkUserUpLine = UserUpline::where('user_id', $checkUserId)->first();

        if (empty($upLine['upline']) && empty($checkUserUpLine['upline'])) {
            return false;
        }

        $line = array_filter(explode(',', $upLine['upline']));
        $checkUserLine = array_filter(explode(',', $checkUserUpLine['upline']));

        if (in_array($checkUserId, $line)) {
            return true;
        }

        if (in_array($userId, $checkUserLine)) {
            return true;
        }

        return false;
    }
}